# -*- coding: utf-8 -*-
import scrapy
# from PIL import Image
# import pytesseract
import json
import lianzhong_api
import re
import requests
import datetime
import time
from scrapy.utils.project import get_project_settings
import pymysql
import base64
setting=get_project_settings()

class elong(scrapy.Spider):

    name = 'elong'

    def __init__(self,*args,**kwargs):
        self.CRS_ID = kwargs['CRS_ID']
        self.username = kwargs['username']
        password = kwargs['password'][1:]
        self.password = base64.b64decode(password).decode()
        self.batch_no = kwargs['batch_no']
        self.now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        print(self.CRS_ID,self.username,self.password)
        self.headers={
            'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
            'accept':'application/json, text/javascript, */*',
            'x-requested-with':'XMLHttpRequest',
            'content-type':'application/json; charset=UTF-8'
        }
        # self.batch_no = datetime.datetime.now().strftime('%Y%m%d')

        HOST = setting.get('HOST')
        PORT = setting.get('PORT')
        USER = setting.get('USER')
        PASSWD = setting.get('PASSWD')
        DB = setting.get('DB')
        CHARSET = setting.get('CHARSET')

        self.conn = pymysql.connect(host=HOST, port=PORT, user=USER, passwd=PASSWD, db=DB, charset=CHARSET)
        self.cur = self.conn.cursor()

        now_time = datetime.datetime.now()
        yesterday = now_time + datetime.timedelta(days=0)
        self.strdate1 = yesterday.strftime('%Y-%m-%d')
        yesterday = now_time + datetime.timedelta(days=6)
        self.strdate2 = yesterday.strftime('%Y-%m-%d')

    def start_requests(self):
        url='https://ebooking.elong.com/ebkauth/login'
        yield scrapy.Request(url, meta={'cookiejar': 1}, callback=self.post_login)

    def post_login(self, response):
        image_url='https://ebooking.elong.com/ebkauth/verifycode/code?type=1'
        yield scrapy.Request(
            image_url,
            meta={
                'cookiejar': response.meta['cookiejar']
            },
            callback=self.get_image,
            dont_filter=True
        )

    def get_image(self, response):
        images=response.body
        with open('image.png','wb') as f:
            f.write(images)

        captchaCode=lianzhong_api.main(
                        'baozhengxing',
                        '1qaz2wsx@123',
                        'image.png',
                        "http://v1-http-api.jsdama.com/api.php?mod=php&act=upload",
                        '4',
                        '4',
                        '1001',
                        ''
                    )
        try:
            captchaCode=json.loads(captchaCode)['data']['val']
            print(captchaCode)
            body = {
                "username":self.username,
                "password":self.password,
                "vcode":captchaCode,
                "freeLogin":True,
                "sdId":9429860
            }

            headers={
                'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
                'accept':'application/json, text/javascript, */*',
                'x-requested-with':'XMLHttpRequest',
                'content-type':'application/json; charset=UTF-8'
            }

            yield scrapy.FormRequest(
                url='https://ebooking.elong.com/ebkauth/loginPost',
                callback=self.after_login,
                dont_filter=True,
                meta={
                    'cookiejar': response.meta['cookiejar']
                },
                headers=headers,
                body=str(json.dumps(body)),
                method='POST'
            )
        except:
            image_url = 'https://ebooking.elong.com/ebkauth/verifycode/code?type=1'
            yield scrapy.Request(
                image_url,
                meta={
                    'cookiejar': response.meta['cookiejar']
                },
                callback=self.get_image
            )


    def after_login(self, response):
        print(response.body.decode('utf-8'))
        code=json.loads(response.body.decode('utf-8'))['code']
        try:
            retdesc = json.loads(response.body.decode('utf-8'))['data']['retdesc']
        except:
            retdesc = ''
        try:
            errorMsg=json.loads(response.body.decode('utf-8'))['errorMsg']
        except:
            errorMsg=''
        if code=='0':
            # yield scrapy.FormRequest(
            #     url='https://ebooking.elong.com/ebkcommon/currentHotel/selectHotelList',
            #     callback=self.parse,
            #     dont_filter=True,
            #     meta={
            #         'cookiejar': response.meta['cookiejar']
            #     },
            #     body='{}',
            #     headers=self.headers,
            #     method='POST'
            # )
            pass
        elif errorMsg=='VcodeError':
            image_url = 'https://ebooking.elong.com/ebkauth/verifycode/code?type=1'
            yield scrapy.Request(
                image_url,
                meta={
                    'cookiejar': response.meta['cookiejar']
                },
                callback=self.get_image,
                dont_filter=True
            )

        elif errorMsg=='UsernameOrPasswrodError':
            print("1111111111111111111111111111111111111111111111111")
            # sql = "update hotel_users set Elong_Status=2 where Elong_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Elong_Username,Elong_Status,Elong_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Elong_Status='%s',Elong_Date='%s',Elong_Username='%s'" % (self.CRS_ID, self.username, 1, self.now, self.batch_no, 1, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()

            # sql="update ota_back_account set status=1 where username=%s"%(self.username)
            # self.cur.execute(sql)
            # self.conn.commit()

        if retdesc=="validte hotel user success!":
            print("0000000000000000000000000000000000000000000000000")
            # sql = "update hotel_users set Elong_Status=0 where Elong_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Elong_Username,Elong_Status,Elong_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Elong_Status='%s',Elong_Date='%s',Elong_Username='%s'" % (self.CRS_ID, self.username, 0, self.now, self.batch_no, 0, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()

        elif retdesc=="需要强制更新密码!":
            print("222222222222222222222222222222222222222222222222")
            # sql = "update hotel_users set Elong_Status=1 where Elong_Username='%s'" % (self.username)
            sql = "insert into ota_back_account_status (CRS_ID,Elong_Username,Elong_Status,Elong_Date,batch_no) values('%s','%s','%s','%s','%s')  on  DUPLICATE key update Elong_Status='%s',Elong_Date='%s',Elong_Username='%s'" % (self.CRS_ID, self.username, 2, self.now, self.batch_no, 2, self.now,self.username)
            self.cur.execute(sql)
            self.conn.commit()

            sql = "update ota_back_account_info set verify_time='%s' where CRS_ID='%s'" % (self.now, self.CRS_ID)
            self.cur.execute(sql)
            self.conn.commit()

